#coding=utf-8

from django.views.generic.simple import direct_to_template
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect
from django.shortcuts import get_object_or_404
from models import User
from forms import UserForm

def show_users(request):
    ''' Shows users list '''
    
    users = User.objects.all()
    
    if users is None or users.count() is 0:
        return check_new_user (request)

    return direct_to_template (request, 'users.html', { 'users': users })

def create_new_user(request):
    ''' Creates form to add new user '''

    form = UserForm ()
    return direct_to_template (request, 'new_user_form.html', { 'form': form, 'has_back': True })

def check_new_user(request):
    ''' Checks validity of new user form '''
    
    return check_user(request, 0)

def edit_user(request, user_id):
    ''' Edit user data '''
    
    user = get_object_or_404 (User, pk=user_id)
    form = UserForm (instance=user)
    return direct_to_template (request, 'user_form.html', { 'form': form, 'user_id': user_id, 'has_back': True })

def check_user(request, user_id):
    ''' Checks validity of user form '''
    
    if request.method == 'POST':
        
        if 'cancel' in request.POST:
            return HttpResponseRedirect (reverse('uzytkownicy'))
            
        form = UserForm (request.POST)
        
        if user_id != 0:
            user = get_object_or_404 (User, pk=user_id)
            form = UserForm (request.POST, instance=user)

        if form.is_valid():
                    
            if 'submit' in request.POST:
                form.save()
                
            return HttpResponseRedirect (reverse('uzytkownicy'))
        
    return direct_to_template (request, 'user_form.html', { 'form': form, 'has_back': True })   

def delete_user(request, user_id):
    ''' Deletes user '''
    
    get_object_or_404 (User, pk=user_id).delete()
